package cn.wolfcode.web.Interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler instanceof HandlerMethod){
        //        判断是否是超级管理员,如果是,则放行,不是则进入判断
        Employee user = (Employee) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        if (user.isAdmin()) {
        return true;
        }

            //        判断是否是贴了权限注解的方法,不是则放行,是则进入判断
            //        handler对象  HandlerMethod
            HandlerMethod method = (HandlerMethod) handler;

            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if (methodAnnotation == null) {
                return true;
            }
                String expression = methodAnnotation.expression();

            if("log:list".equals(expression)){
                response.sendRedirect("/noPermission");
                return false;
            }
                List<Permission> permissions = (List<Permission>) request.getSession().getAttribute(UserContext.PERMISSION_IN_SESSION);
            //        判断该成员是否拥有该权限表达式,是则放行,不是则进入判断

                for (Permission perm : permissions) {
                    if (perm.getExpression().equals(expression)) {
                        return true;
                    }}

                        //        判断是否贴了ResponseBody,如果不是则返回没有权限的界面,是则相应一个JsonResult对象
                            if(method.getMethodAnnotation(ResponseBody.class) == null){
                                response.sendRedirect("/noPermission");
                                return false;
                            }
                            else{
                                response.setContentType("application/json;charset=utf-8");
                                String responseData = JSON.toJSONString(new JsonResult(false,"您没有权限操作"));
                                response.getWriter().write(responseData);
                            }
                    }
        return true;
    }

}
